package com.alameda.filestorage.business.impl;

import com.alameda.filestorage.business.service.FileStorageComponent;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * 文件上传 业务逻辑层 具体实现
 *
 * @author Lv
 * @date 2024/11/23
 */
@Service
public class FileStorageComponentImpl implements FileStorageComponent {

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 基础路径
     */
    @Value("${machine.file.base-path}")
    private String basePath;

    /**
     * 文件存储路径
     */
    @Value("${machine.file.storage-path}")
    private String storagePath;

    /**
     * 存储机器位置
     */
    @Value("${machine.file.domain}")
    private String ip;

    /**
     * 上传文件
     *
     * @param multipartFile 文件对象
     * @return 文件信息
     */
    @Override
    public FileInfo upload(MultipartFile multipartFile) {
        FileInfo fileInfo = fileStorageService.of(multipartFile).upload();
        Path oldPath = Paths.get(storagePath + File.separator + basePath + File.separator + fileInfo.getFilename());
        Path newPath = Paths.get(storagePath + File.separator + basePath + File.separator + multipartFile.getOriginalFilename());

        try {
            // 重命名文件
            Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }

        fileInfo.setUrl(ip + basePath + multipartFile.getOriginalFilename());
        fileInfo.setFilename(multipartFile.getOriginalFilename());
        return fileInfo;
    }

    /**
     * 上传文件
     *
     * @param multipartFile 文件对象
     * @return 文件路径
     */
    @Override
    public String uploadFile(MultipartFile multipartFile) {
        FileInfo upload = upload(multipartFile);
        return upload.getUrl();
    }

    /**
     * 上传图片
     *
     * @param multipartFile 文件对象
     * @return 文件信息
     */
    @Override
    public FileInfo uploadImage(MultipartFile multipartFile) {
        return fileStorageService.of(multipartFile)
                //将图片大小调整到 1000*1000
                .image(img -> img.size(1000, 1000))
                //再生成一张 200*200 的缩略图
                .thumbnail(th -> th.size(200, 200))
                .upload();
    }

    /**
     * 上传文件
     *
     * @param request http请求对象
     * @return 文件信息
     */
    @Override
    public FileInfo uploadPlatform(HttpServletRequest request) {
        return fileStorageService.of(request).upload();
    }
}
